<?php

class Myzen_Oauth_Query {
    
    protected $_client;

    protected $_baseURL;
    
    public function __construct() {
      
      try{
	    $accessToken = unserialize(Zend_Registry::get('app_session')->accessToken);
      } catch(Zend_Exception $e) {
        throw(new Myzen_Oauth_Exception('issue while getting accessToken from registry: '.$e->getMessage()));	
      }

      $this->_client = $accessToken->getHttpClient(Zend_Registry::get('app_config')->oauth->toArray());

      $this->_client->setMethod(Zend_Http_Client::POST);
      $this->_client->setOptions(array( 'requestScheme' => Zend_Oauth::REQUEST_SCHEME_POSTBODY));
      $this->_baseURL = Zend_Registry::get('app_config')->oauth->baseUrl;    	

    }
    
    public function query($module,$controller,$action,$data = '') {

		if(!empty($data) && is_array($data)) {
			foreach($data as $key => $value) {
				Zend_Registry::get('app_log')->log('parameter:'.$key.'-'.$value,7); 
    			$this->_client->setParameterPost($key, $value);
			}
		}

	Zend_Registry::get('app_log')->log('Calling back end:'.$this->_baseURL.$module.'/'.$controller.'/'.$action.'/',6);
    	$this->_client->setUri($this->_baseURL.$module.'/'.$controller.'/'.$action.'/');
//Zend_Registry::get('app_log')->log('query:'.serialize($this->_client),7);
    	try{
    		$response = $this->_client->request();
    		$result = $response->getBody();
    	} catch(Zend_Http_Client_Adapter_Exception $e) {
    		$resultData = array('status' => 'KO','error' => array('num' => 1,'message' => 'timeout of the server'));
    		if(isset($data['output']) && $data['output'] == 'simplexml') $result = '<rsp><status>KO</status><error><num>1</num><message>timeout of the server</message></error></rsp>';
    		elseif(isset($data['output']) && $data['output'] == 'json') $result = json_encode($resultData);
    		else $result = serialize($resultData);
    	}

	Zend_Registry::get('app_log')->log($result,7);  
    	return $result;  	

    } //end query
    
} //end class  
